﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Maticsoft.DAL;
using System.Reflection;
using System.IO;
using BuildingForm.Common;

namespace BuildingForm.PersonInfo
{
    public partial class PersonPassInOut : Form 
    {
        public PersonPassInOut()
        {
            InitializeComponent();
            Init();
            bind();
        }
        private void Init()
        {
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ShowIcon = false;
            //表头加粗，居中
            foreach (DataGridViewColumn col in this.dataGridView1.Columns)
            {
                col.SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            this.dataGridView1.ColumnHeadersDefaultCellStyle.Font = new System.Drawing.Font("SimSun", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
            this.dataGridView1.AllowUserToAddRows = false;
            //班组
            Maticsoft.DAL.Banz_Info info = new Banz_Info();
            DataTable dt = info.GetList("").Tables[0];
            List<string> strList = new List<string>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                strList.Add(dt.Rows[i]["bzmc"].ToString().Trim());
            }
            List<string> list = new List<string>();
            list.Add("全部");
            list.AddRange(strList);
            this.cboTeam.DataSource = list;
            this.picDate.Value = DateTime.Now;
        }
        private List<int> arr = new List<int>();
        public List<SJInfo> sjList = new List<SJInfo>();
       

        private List<EntryExitInfo> bind()
        {
            List<InOutInfo> list = new List<InOutInfo>();
            List<InOutData> datas = new List<InOutData>();
            Maticsoft.DAL.Kqjl_Info info = new Kqjl_Info();
            string sql = string.Empty;
            sql = " 1=1 ";
            string team = this.cboTeam.Text.ToString().Trim();
            if (team != "全部")
            {
                sql += " and d.bzmc='" + team + "'";
            }
            string time = this.picDate.Value.ToString("yyyy-MM-dd");
            sql += " and CONVERT(varchar(10),kqsj,120)='" + time + "'";
            sql += " order by sfzh,kqsj ";
            DataTable dt = info.GetListByPersonPassInOut(sql).Tables[0];
            string sfzh_b = string.Empty;
            string dksj_b = string.Empty;
            DateTime beginTime = DateTime.MinValue;
            DateTime endTime = DateTime.MinValue;
            InOutInfo ninfo = new InOutInfo();
            
            decimal worktime = 0;
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                DataRow dr = dt.Rows[i];
                string sfzh_1 = dr["sfzh"].ToString();
                bool isEnter = Convert.ToBoolean(dr["jczt"]);
                if (sfzh_1 == sfzh_b)
                {
                    if (isEnter)
                    {
                        beginTime = Convert.ToDateTime(dr["kqsj"]);
                    }
                    else
                    {
                        endTime = Convert.ToDateTime(dr["kqsj"]);
                        if (beginTime != DateTime.MinValue)
                        {
                            TimeSpan ts = endTime - beginTime;
                            decimal di = ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
                            worktime += di;
                            SJInfo sj = new SJInfo();
                            sj.sfzh = sfzh_1;
                            sj.content = beginTime.ToString("HH:mm") + "-" + endTime.ToString ("HH:mm") + "; ";
                            sj.num = 0;
                            sjList.Add(sj);
                            //防止一个人一天的再次
                            beginTime = DateTime.MinValue;
                            endTime = DateTime.MinValue;
                        }
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(sfzh_b))
                    {
                        if (isEnter)
                        {
                           beginTime = Convert.ToDateTime(dr["kqsj"]);
                        }
                    }
                    else
                    {
                        if (isEnter)
                        {
                            beginTime = Convert.ToDateTime(dr["kqsj"]);
                        }
                        else
                        {
                            beginTime = DateTime.MinValue;
                        }
                        List<SJInfo> sjList2 = new List<SJInfo>();
                        sjList2 = sjList;
                        
                        ninfo.datas = sjList2;
                        sjList = new List<SJInfo>();
                        //sjList.Clear();
                        ninfo.zcsj = Math.Round(worktime / 3600, 2);
                        datas = new List<InOutData>();
                        InOutInfo entity = new InOutInfo();
                        entity = ninfo;
                        list.Add(entity);
                        ninfo = new InOutInfo();
                       
                    }
                    sfzh_b = sfzh_1;
                    worktime = 0;
                    ninfo.bz = dr["bz"].ToString();
                    ninfo.bzmc=dr["bzmc"].ToString ();
                    ninfo.gh = dr["gh"].ToString();
                    ninfo.kh = dr["kh"].ToString();
                    ninfo.sfzh = dr["sfzh"].ToString();
                    ninfo.xm = dr["xm"].ToString();
                    ninfo.xb = dr["xb"].ToString();
                    ninfo.gz = dr["gz"].ToString();
                }
                //InOutData data = new InOutData();
                //data.kqsj = dr["kqsj"].ToString();
                //data.zt = isEnter ? "进" : "出";
                //datas.Add(data);
            }
            ninfo.datas = sjList;
            ninfo.zcsj = Math.Round(worktime / 3600, 2);
            list.Add(ninfo);
            List<EntryExitInfo> lists = new List<EntryExitInfo>();
            int num = 0; int kk = 0;
            arr.Clear();
            arr.Add(0);

            foreach (var l in list)
            {
                if (l.datas.Count == 0) continue;
                if (l.zcsj == 0) continue;
                if (l.datas.Count > 0)
                {
                    num++;
                }
                EntryExitInfo obj = new EntryExitInfo();
                    obj.bz = l.bz;
                    obj.bzmc = l.bzmc;
                    obj.gh = l.gh;
                    obj.kh = l.kh;
                    //obj.kqsj = data.kqsj;
                    obj.sfzh = l.sfzh;
                    obj.xh =kk;
                    obj.xh2 = num;
                    obj.xm = l.xm;
                    obj.zcsj = l.zcsj;
                    obj.gz = l.gz;
                    obj.xb = l.xb;
                var jj=0;
                    //lists.Add(obj);
                foreach (var data in l.datas)
                {
                    jj++;
                    if (jj % 3 == 0 || jj == l.datas.Count)
                    {
                        obj.kqsj += data.content;
                        kk++;
                        obj.xh = kk;
                        EntryExitInfo obj2 = new EntryExitInfo();
                        obj2 = obj;
                        lists.Add(obj2);
                        obj = new EntryExitInfo();
                        obj.bz = l.bz;
                        obj.bzmc = l.bzmc;
                        obj.gh = l.gh;
                        obj.kh = l.kh;
                        obj.sfzh = l.sfzh;
                        obj.xh = kk + 1;
                        obj.xh2 = num;
                        obj.xm = l.xm;
                        obj.zcsj = l.zcsj;
                        obj.gz = l.gz;
                        obj.xb = l.xb;
                        obj.kqsj = "";
                    }
                    else
                    {
                        obj.kqsj += data.content;
                    }
                }
                if (l.datas.Count > 0)
                {
                    arr.Add(kk);
                }
                
            }

            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = lists;
            //
            sjList = new List<SJInfo>();
            return lists;
        }
   

        private void button1_Click(object sender, EventArgs e)
        {
            bind();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                Sys_Info dao = new Sys_Info();
                string name = string.Empty;
                DataTable dtt = dao.GetList("").Tables[0];
                if (dtt.Rows.Count > 0)
                {
                    name = dtt.Rows[0]["gcmc"].ToString();
                }
                List<EntryExitInfo> list = bind();
                
                //List<WorkTime> list2 = GetWorkTimeList();
                //foreach (var l in list)
                //{
                //    foreach (var ll in list2)
                //    {
                //        if (l.sfzh == ll.sfzh)
                //        {
                //            l.dykq = ll.dygs; break;
                //        }
                //    }
                //}
                if (list.Count == 0)
                {
                    MessageBox.Show("没有数据！"); return;
                }
                string team = this.cboTeam.Text.ToString();
                if (team == "全部") team = "所有人员";
                team = team + "," + name;
                string time = this.picDate.Value.ToString("yyyy年MM月dd日");
                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                //设置文件类型   
                saveFileDialog1.Filter = " xls files(*.xls)|*.xls";
                //设置默认文件类型显示顺序   
                saveFileDialog1.FilterIndex = 2;
                //保存对话框是否记忆上次打开的目录   
                saveFileDialog1.RestoreDirectory = true;
                saveFileDialog1.FileName = "劳务人员日考勤表" + DateTime.Now.ToString("yyyyMMdd");
                //点了保存按钮进入   
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                 {
                    string fileName = saveFileDialog1.FileName;
                    string[] oldCols = new string[] { "xh2","xm","xb","bzmc", "gz","sfzh","kqsj",  "zcsj"};
                    string[] newCols = new string[] { "编号",  "工人姓名","性别","班组","工种", "身份证号", "进出场时间",   "当日工时（小时）"};
                    //DataTable dt = ConvertHelper.ToDataSet(ConvertToList(list)).Tables[0];
                    DataTable dt = ConvertHelper.ToDataSet(list).Tables[0];
                    ExcelHelper.ExportByPersonPassInOut(dt, "劳务人员日考勤表", fileName, "Sheet1", oldCols, newCols, arr, team, time);
                    MessageBox.Show("导出文件成功！"); return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出文件故障！"); return;
            }
        }
        //public List<EntryExitInfo> ConvertToList(List<EntryExitInfo> list)
        //{
        //    arr.Clear();
        //    arr.Add(0);
        //    List<EntryExitInfo> list2 = new List<EntryExitInfo>();
        //    string nkqsj = "";
        //    var i = 0;
        //    var k = 0;
        //    for (var j = 0; j < list.Count; j++)
        //    {
        //        var l = list[j];
        //        nkqsj += Convert.ToDateTime(l.kqsj).ToString("HH:mm") + l.zt + "  ";
        //        i++;
        //        if (j == list.Count - 1)
        //        {
        //            k++;
        //            EntryExitInfo eet = new EntryExitInfo();
        //            eet.bz = l.bz;
        //            eet.dykq = l.dykq;
        //            eet.gh = l.gh;
        //            eet.kh = l.kh;
        //            eet.kqsj = l.kqsj;
        //            eet.nkqsj = nkqsj;
        //            eet.sfzh = l.sfzh;
        //            eet.wcqyy = "";
        //            eet.xh = k;
        //            eet.xm = l.xm;
        //            eet.zcsj = l.zcsj;
        //            eet.zt = l.zt;
        //            eet.gz = l.gz;
        //            eet.xb = l.xb;
        //            list2.Add(eet);
        //            arr.Add(k);
        //            break;
        //        }
        //        if (list[j].sfzh != list[j + 1].sfzh || i == 6)
        //        {
        //            k++;
        //            EntryExitInfo eet = new EntryExitInfo();
        //            eet.bz = l.bz;
        //            eet.dykq = l.dykq;
        //            eet.gh = l.gh;
        //            eet.kh = l.kh;
        //            eet.kqsj = l.kqsj;
        //            eet.nkqsj = nkqsj;
        //            eet.sfzh = l.sfzh;
        //            eet.wcqyy = eet.wcqyy;
        //            eet.xh = k;
        //            eet.xm = l.xm;
        //            eet.zcsj = l.zcsj;
        //            eet.zt = l.zt;
        //            eet.gz = l.gz;
        //            eet.xb = l.xb;
        //            list2.Add(eet);
        //            i = 0;
        //            nkqsj = "";
        //            if (list[j].sfzh != list[j + 1].sfzh)
        //            {
        //                arr.Add(k);
        //            }
        //        }
        //    }
        //    return list2;
        //}
        private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            // 对第1列相同单元格进行合并
            if ((e.ColumnIndex ==8) && e.RowIndex != -1)
            {
                using
                    (
                    Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),
                    backColorBrush = new SolidBrush(e.CellStyle.BackColor)
                    )
                {
                    using (Pen gridLinePen = new Pen(gridBrush))
                    {
                        // 清除单元格
                        e.Graphics.FillRectangle(backColorBrush, e.CellBounds);

                        // 画 Grid 边线（仅画单元格的底边线和右边线）
                        //   如果下一行和当前行的数据不同，则在当前的单元格画一条底边线
                        //if (e.RowIndex < dataGridView1.Rows.Count - 1 &&
                        //dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() !=
                        //e.Value.ToString())
                        //    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                        //    e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                        //    e.CellBounds.Bottom - 1);
                        // 画右边线
                        e.Graphics.DrawLine(gridLinePen, e.CellBounds.Right - 1,
                            e.CellBounds.Top, e.CellBounds.Right - 1,
                            e.CellBounds.Bottom);

                        // 画（填写）单元格内容，相同的内容的单元格只填写第一个
                        if (e.Value != null)
                        {
                            //if (e.RowIndex > 0 &&
                            //dataGridView1.Rows[e.RowIndex - 1].Cells[e.ColumnIndex].Value.ToString() ==
                            //e.Value.ToString())
                            //{ }
                            //else
                            //{
                            //    e.Graphics.DrawString(e.Value.ToString (), e.CellStyle.Font,
                            //        Brushes.Black, e.CellBounds.X + 2,
                            //        e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            //}
                            //
                            if (arr.Contains(e.RowIndex + 1))
                            {
                                //底边线
                                //if (e.RowIndex < dataGridView1.Rows.Count - 1 &&
                                //dataGridView1.Rows[e.RowIndex + 1].Cells[e.ColumnIndex].Value.ToString() !=
                                //e.Value.ToString())
                                    e.Graphics.DrawLine(gridLinePen, e.CellBounds.Left,
                                    e.CellBounds.Bottom - 1, e.CellBounds.Right - 1,
                                    e.CellBounds.Bottom - 1);

                            }
                            if (arr.Contains(e.RowIndex))
                            {
                                e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font,
                                   Brushes.Black, e.CellBounds.X + 2,
                                   e.CellBounds.Y + 5, StringFormat.GenericDefault);
                            }
                        }
                        e.Handled = true;
                    }
                }
            }
        }
    }

    public class InOutInfo
    {
        public int xh { get; set; }
        public string gh { get; set; }
        public string sfzh { get; set; }
        public string xm { get; set; }
        public string bz { get; set; }
        public string kh { get; set; }
        public string xb { get; set; }
        public string gz { get; set; }
        public List<SJInfo> datas { get; set; }
        public decimal zcsj { get; set; }
        public string bzmc { get; set; }
    }
    public class InOutData
    {
        public string kqsj { get; set; }
        public string zt { get; set; }
    }
    public class SJInfo
    {
        public string sfzh { get; set; }
        public string content { get; set; }
        public int num { get; set; }
    }
    public class EntryExitInfo
    {
        public int xh { get; set; }
        public int xh2 { get; set; }
        public string gh { get; set; }
        public string sfzh { get; set; }
        public string xm { get; set; }
        public string bz { get; set; }
        public string kh { get; set; }
        public string kqsj { get; set; }
        public string zt { get; set; }
        public decimal zcsj { get; set; }
        public string wcqyy { get; set; }
        public decimal dykq { get; set; }
        public string nkqsj { get; set; }
        public string xb { get; set; }
        public string gz { get; set; } 
        public string bzmc { get; set; }
    }

}
